package com.zr.controller;

import com.zr.pojo.User;
import com.zr.service.UserService;
import com.zr.util.SendMail;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    private Random random = new Random();
    //随机生成begin和end之间的一个int值
    private int randNum(int begin, int end) {
        return random.nextInt(end - begin) + begin;
    }
    //跳转至登录页面
    @RequestMapping("/to_login")
    public String to_login(){
        return "/login";
    }
    //跳转至注册页面
    @RequestMapping("/to_register")
    public String to_register(){
        return "/register";
    }
    //登录验证
    @RequestMapping("/loginCheck")
    public String loginCheck(String username,String pwd,String captcha_1,HttpServletRequest request){
        String valicode = request.getSession().getAttribute("Valicode").toString();
        if(valicode!=null){
            boolean b = valicode.equalsIgnoreCase(captcha_1);
            if(b){
                User user = userService.selectOneByUidAndPassword(username, pwd);
                if(user!=null){
                    request.getSession().setAttribute("userSession",user);
                    return "/index";
                }else {
                    request.getSession().setAttribute("u_msg","账号或密码错误！");
                    return "/login";
                }

            }else{
                request.getSession().setAttribute("u_msg","验证码输入错误！");
                return "/login";
            }
        }

        return "/login";
    }
    //账号是否可用
    @ResponseBody
    @RequestMapping("/uidCheck/{uid}")
    public String uidCheck(@PathVariable String uid){
        User user = userService.selectOneByUid(uid);
        if(user==null){
            return "ok";//uid可用
        }
        return "error";
    }
//登录验证码生成
    @ResponseBody
    @RequestMapping("/yzm")
    public void yzm(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 首先设置浏览器不缓存
        response.setHeader("cache-control", "no-cache");

        response.setHeader("Expire", "-1"); // >0为缓存

        response.setHeader("pragma", "no-cache");

        // 存储正确的验证码

        String vali_code = "";

        String Vali_str = "abcdefghijklmnopqrstuvwsyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        Color[] colors =

                { Color.BLACK, Color.RED, Color.BLUE };

        // 1.创建图像

        int width = 110, height = 40;

        int x_offset = 5, y_offset = 28;

        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);

        // 2.创建画布

        Graphics2D g = img.createGraphics();

        // 3.为画布添加背景颜色为亮灰色

        g.setColor(Color.LIGHT_GRAY);

        g.fillRect(0, 0, width, height);//fillRect是包括矩形框内部

        // 4.为画布添加边框

        g.setColor(Color.BLUE);

        g.drawRect(0, 0, width - 1, height - 1);//drawRect是绘制矩形边框

        // 5.绘制干扰线

        for (int i = 0; i < 10; i++)
        {
            g.setColor(new Color(randNum(0, 255), randNum(0, 255), randNum(0, 255)));

            g.drawLine(randNum(0, width), randNum(0, height), randNum(0, width), randNum(0, height));

        }
        g.setFont(new Font("黑体", Font.BOLD, 20));
        for (int i = 0; i < 4; i++)
        {
            int r = randNum(-180, 180);

            String code = Vali_str.charAt(randNum(0, Vali_str.length() - 1)) + "";

            g.rotate(r / 180 * Math.PI);

            g.setColor(colors[randNum(0, colors.length)]);

            g.drawString(code, x_offset + i * 30, y_offset);

            g.rotate(-r / 180 * Math.PI);

            vali_code += code;

        }

        //将验证码的内容存储在HttpSession中

        HttpSession session = request.getSession();

        session.setAttribute("Valicode", vali_code);

        // 通过response的输出流打给浏览器

        ImageIO.write(img, "jpg", response.getOutputStream());
    }
//邮箱验证码生成
    @ResponseBody
    @RequestMapping("/mailActivate")
    public void mailActivate(@RequestParam("email") String receiveMailAccount ,HttpServletRequest request)throws Exception{
//        String receiveMailAccount="2462527100@qq.com";
//        String receiveMailAccount="847243088@qq.com";
//        String receiveMailAccount="1228839580@qq.com";
//        System.out.println(receiveMailAccount);
//        System.out.println("1");

        HttpSession session = request.getSession();
        if(session.getAttribute("zcyzm")!=null){
           long nowTime=new Date().getTime();
           long zcTime=(long)session.getAttribute("zcTime");
           if(nowTime-zcTime>1000*60*10){
               session.removeAttribute("zcyzm");
               session.removeAttribute("zcTime");
           }
        }
        if(session.getAttribute("zcyzm")==null) {
            session.setAttribute("zcTime",new Date().getTime());
            String yzm= UUID.randomUUID().toString();
            request.getSession().setAttribute("zcyzm",yzm);
            //邮件内容
            String messageContent="<html><head></head><body><h1>这是一封天天生鲜注册验证邮件,验证码为：</h1><h3>"+
                    yzm
                    + "</h3></body></html>";
            //发件人显示昵称
            String fromPersonl="天天生鲜";
            //收件人显示昵称
            String toPersonl="帅哥亦或美女";
            //邮件主题
            String subject ="注册验证码";
            SendMail.sendMail(receiveMailAccount,messageContent,fromPersonl,toPersonl,subject);
//        System.out.println("2");
        }

    }

   //注册验证
    @RequestMapping("/registerCheck")
    public String registerCheck(String user_name,String pwd,String email,String mailYzm,HttpServletRequest request){
        HttpSession session=request.getSession();
        String zcyzm = (String) session.getAttribute("zcyzm");
        if(!Objects.equals(zcyzm,mailYzm)){
            return "/register";
        }else {
            long nowTime=new Date().getTime();
           long zcTime=(long)session.getAttribute("zcTime");
           //验证码有效期10分钟
           if(nowTime-zcTime>1000*60*10){

               return "/register";
           }else {
               session.removeAttribute("zcyzm");
               User user=new User();
               user.setUid(user_name);
               user.setPassword(pwd);
               user.setEmail(email);
               Integer integer = userService.insertOne(user);
               return "/login";
           }

        }
    }

























    //    @RequestMapping("/to_add")

//    public String to_add(){
//        return "add";
//    }
//    @RequestMapping("/add")
//    public String add(HttpServletRequest request, Student student , MultipartFile upload){
//    String path=request.getSession().getServletContext().getRealPath("/upload/");
//    File file=new File(path);
//    if(!file.exists()){
//        file.mkdirs();
//    }
//        String filename = upload.getOriginalFilename();
//        String newFileName = UUID.randomUUID().toString().replace("-", "")+filename;
//        try {
//            upload.transferTo(new File(path,filename));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        studentService.add(student);
////        for (Object o : new ArrayList<>()) {
////
////        }
//        return "redirect:/student/list";
//    }
//    @RequestMapping("/to_list")
//    public String to_list(){
//        return "list";
//    }
//    @RequestMapping("/list")
//    public String list(@RequestParam(defaultValue = "1") Integer pageNum, Model model){
//        PageInfo<Student> studentPageInfo = studentService.selectByPage(pageNum, 5);
//        model.addAttribute("pageInfo",studentPageInfo);
//        return "list";
//    }
//    @RequestMapping("/to_find")
//    public String to_find(){
//        return "find";
//    }
//
//    @RequestMapping(value = "/findOne",method = RequestMethod.POST)
//   @ResponseBody
//
//    public Student to_find(@RequestBody Student student){
//        System.out.println(student);
//        Student student1 = studentService.selectOne(student);
//        System.out.println(student1.getSno());
//        System.out.println(student1.getSname());
//        System.out.println(student1.getBirthday());
//        return student1;
//    }
//
//    @RequestMapping("/to_redisList")
//    public String to_redisList(){
//        return "redisList";
//    }
////    @RequestMapping(value = "/redisTest1",produces = "text/html;charset=UTF-8")
//@RequestMapping(value = "/redisTest1",produces = "application/json;charset=UTF-8")
////    @PostMapping("/redisTest1")
//    @ResponseBody
//    public String redisTest1(){
//
//
//        return studentService.selectAll();
//    }
//

}
